from django.db.models import F
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
import datetime


# Create your views here.


class SectorView(APIView):
    def get(self, request):
        set = SectorModel.objects.filter(level=1)
        return Response(SectorSer(set, many=True).data)


class UserView(APIView):
    def post(self, request):
        name = request.data.get('name')
        user = UserModel.objects.filter(name=name).first()
        if user:
            if user.state == str(0):
                user.state = 1
                user.save()
                RecordModel.objects.create(user_id=user.id, sector_id=user.sector.id)
                return Response({'msg': '上班', 'code': 200})
            else:
                return Response({'msg': '正在工作中', 'code': 300})
        else:
            return Response({'msg': '没有该员工', 'code': 400})

    def get(self, request):
        sector_id = request.GET.get('sector_id')
        user = UserModel.objects.filter(sector_id=sector_id)
        return Response(UserSer(user, many=True).data)

    def put(self, request):
        user_id = request.data.get('user_id')
        user = UserModel.objects.filter(id=user_id).first()
        if user:
            user.sector_id = user.sector.sector_id
            user.save()
            return Response({'msg': '成功', 'code': 200})
        return Response({'msg': '失败', 'code': 400})


class RecordView(APIView):
    def put(self, request):
        user_id = request.data.get('user_id')
        sector_id = request.data.get('sector_id')
        total = SectorModel.objects.filter(id=sector_id).first().total
        record = RecordModel.objects.filter(user_id=user_id, total=None).first()
        if record:
            end = datetime.datetime.now()
            time = (end - record.start).total_seconds() / 3600
            new_total = round(total * time, 2)
            record.end = end
            record.time = time
            record.total = new_total
            record.save()
            UserModel.objects.filter(id=user_id).update(total=F('total')+new_total, state=0)
            return Response({'msg': '下班', 'code': 200})
        return Response({'msg': '失败', 'code': 400})

    def get(self, request):
        name = request.GET.get('name')
        set = RecordModel.objects.filter(user__name=name).order_by('-start')
        ser = RecordSer(set, many=True).data
        return Response(ser)
